namespace Warehouse

open System
open System.Windows.Data
open System.Windows.Controls
open FSharp.Windows
open Warehouse.Controls

[<AbstractClass>]
type UpcQuantityPasteModel() = 
    inherit Model()

    [<DefaultValue>] 
    val mutable Items : (string * int) [] 

    abstract Text : string with get, set
    abstract OKEnabled : bool with get, set

type UpcQuantityPasteEvents =
    | ItemsChanged 

type UpcQuantityPasteView() as this = 
    inherit View<UpcQuantityPasteEvents, UpcQuantityPasteModel, UpcQuantityListWindow>()
    
    do
        this.DefaultOKButton <- this.Control.OK
        
    override this.EventStreams = 
        [ 
            this.Control.Items.TextChanged |> Observable.mapTo ItemsChanged
        ] 

    override this.SetBindings model = 

        Binding.FromExpression(
            <@ 
                this.Control.Items.Text <- model.Text
            @>,
            updateSourceTrigger = UpdateSourceTrigger.PropertyChanged
        )

        Binding.FromExpression
            <@ 
                this.Control.OK.IsEnabled <- model.OKEnabled
            @>

type UpcQuantityPasteController(?repository) = 
    inherit Controller<UpcQuantityPasteEvents, UpcQuantityPasteModel>()

    override this.InitModel model = 
        model.OKEnabled <- false

    override this.Dispatcher = function
        | ItemsChanged -> Sync this.ItemsChanged

    member this.ItemsChanged model = 
        try 
            model.Items <- 
                [| 
                    for line in model.Text.Split([|Environment.NewLine|], StringSplitOptions.RemoveEmptyEntries) ->
                        match line.Split(',') with
                        | [| upc; quantity|] when int quantity > 0 -> upc, int quantity
                        | _ -> 
                            invalidArg "Text" "Incorrect format."
                |]
            model.OKEnabled <- model.Items.Length > 0
        with e ->
            model |> Validation.setError <@ fun m -> m.Text @> e.Message
            model.OKEnabled <- false
        

        
